<template>
  <div class="toLogin">
    <el-form
      ref="loginRef"
      :model="ruleForm"
      :rules="rules"
      label-width="70px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" show-password></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
import { ElForm } from 'element-plus';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import cache from '@/utils/cache';
export default defineComponent({
  name: 'tologin',
  components: {},
  setup() {
    const store = useStore();
    const router = useRouter();
    const ruleForm = reactive({
      name: cache.getCache('name') ? cache.getCache('name') : '',
      password: cache.getCache('password') ? cache.getCache('password') : ''
    });
    const rules = {
      name: [
        {
          required: true,
          message: '请输入账号',
          trigger: 'blur'
        },
        {
          pattern: /^[A-Z|a-z|0-9]{5,10}$/,
          message: '用户名必须是5-10个字母或数字',
          trigger: 'blur'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          pattern: /^[a-z0-9]{3,}$/,
          message: '用户密码必须是3位以上数字',
          trigger: 'blur'
        }
      ]
    };
    const loginRef = ref<InstanceType<typeof ElForm>>();
    const actionSubmint = (isKeepLogin: boolean) => {
      loginRef.value?.validate((valid) => {
        if (valid) {
          if (isKeepLogin) {
            cache.setCache('name', ruleForm.name);
            cache.setCache('password', ruleForm.password);
          } else {
            cache.deleteCache('name');
            cache.deleteCache('password');
          }
          store.dispatch('login/loginAction', { ...ruleForm });
        }
      });
    };

    return {
      ruleForm,
      rules,
      actionSubmint,
      loginRef,
      router,
      store
    };
  }
});
</script>

<style lang="less"></style>
